package com.zhiwang.planet.download.filedownloader

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.event.AppDownLoadProgressEvent
import com.zhiwang.planet.util.installIntent
import org.greenrobot.eventbus.EventBus
import java.io.File

@SuppressLint("StaticFieldLeak")
object FileDownLoadManager {

    val TAG = "FileDownLoadManager"

    //url -> progress
    var downloadProgressMap = hashMapOf<String, Int>()

    //url -> taskid
    var downloadIdMap = hashMapOf<String, Int>()

    var urlNameMap = hashMapOf<String, String>()

    // url  -> filename
    var nameMap = hashMapOf<String, String>()

    lateinit var context: Context

    fun holdContext(ctx: Context) {
        context = ctx
    }

    fun download(url: String, name: String?, dir: String) {

        val id = FileDownloader.getImpl()
                .create(url)
                .setForceReDownload(false)
                .setPath(File(dir, name?.plus(".apk")
                        ?: getFileNameWithUrl(url)).absolutePath, false)
                .setCallbackProgressTimes(15)
                .setListener(object : FileDownloadListener() {

                    override fun warn(task: BaseDownloadTask) {

                    }

                    override fun completed(task: BaseDownloadTask) {
                        val event = AppDownLoadProgressEvent(progress = "100", name = name
                                ?: "unknown")
                        event.apkFile = File(task.path)
                        EventBus.getDefault().post(event)
                        context.startActivity(event.apkFile?.installIntent(context))
                    }

                    override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                    }

                    override fun error(task: BaseDownloadTask, e: Throwable?) {
                        CrashReport.postCatchedException(e)
                    }

                    override fun started(task: BaseDownloadTask) {
                        //下载开始，开始记录 进度
                        downloadProgressMap[url] = 0
                        urlNameMap[url] = name ?: "unknown"
                    }

                    override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                        val progress = Math.round(soFarBytes.toFloat() / totalBytes * 100)

                        if (BuildConfig.DEBUG)
                            Log.i(TAG, "progress: $progress")

                        downloadProgressMap[url] = progress
                        EventBus.getDefault().post(AppDownLoadProgressEvent(progress = progress.toString(), name = name
                                ?: ""))
                    }

                    override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                    }

                })
                .start()

        downloadIdMap[url] = id

    }

    private fun getFileNameWithUrl(url: String): String? {
        if (url.endsWith(".apk") && url.lastIndexOf('/') != -1) {
            return url.substring(url.lastIndexOf('/') + 1)
        }

        //取后五个字符组成的字符串作为 文件名
        return url.substring(url.length - 5, url.length).plus(".apk")
    }


    fun pause(url: String) = FileDownloader.getImpl().pause(downloadIdMap[url]!!)

    fun pause(id: Int) {
        FileDownloader.getImpl()
                .pause(id)
    }
}